package shuimin.weixin;


import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 微信相关配置类---系统启动时从properties文件中初始化
 * Created by sky on 16/5/17.
 */
public class Config {

    private static Map<String, Object> CONFIG_POOL = new HashMap<>();

    public static final String CORP_ID = "corp_id";
    public static final String SECRET = "secret";
    public static final String AGENT_ID = "agent_id";
    public static final String AGENT_TOKEN = "token";


//    private String agentId;
//
//    private String token;
//    private String encodingAesKey;


    public static void init(Properties prop) {
        for (Object o : prop.keySet()) {
            String key = String.valueOf(o);
            if (CORP_ID.equals(key)) {
                CONFIG_POOL.put(CORP_ID, prop.get(CORP_ID));
            }
            if (SECRET.equals(key)) {
                CONFIG_POOL.put(SECRET, prop.get(SECRET));
            }
            if (key.endsWith(AGENT_ID)) {
                String app = key.substring(0, key.indexOf(AGENT_ID) - 1);
                Map<String, Object> app_map = app(app);
                app_map.put(AGENT_ID, prop.get(key));
                CONFIG_POOL.put(app, app_map);
            }
            if (key.endsWith(AGENT_TOKEN)) {
                String app = key.substring(0, key.indexOf(AGENT_TOKEN) - 1);
                Map<String, Object> app_map = app(app);
                app_map.put(AGENT_TOKEN, prop.get(key));
                CONFIG_POOL.put(app, app_map);
            }

        }
    }

    public static String getCorpId() {
        return String.valueOf(CONFIG_POOL.get(CORP_ID));
    }

    public static String getSecret() {
        return String.valueOf(CONFIG_POOL.get(SECRET));
    }

    public static String getAgentId(String app) {
        return String.valueOf(app(app).get(AGENT_ID));
    }

    public static String getToken(String app){
        return String.valueOf(app(app).get(AGENT_TOKEN));
    }

    private static Map<String, Object> app(String appName) {
        Object app = CONFIG_POOL.get(appName);
        if (app == null) return new HashMap<>();
        return (Map<String, Object>) app;
    }

}
